package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("friend")
public class FriendController {

    @Autowired
    private FriendService friendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserClient userClient;
    @Autowired
    private NoFriendService noFriendService;

    //1.推荐好友列表的添加好友或非好友(关注或不喜欢)
    @PutMapping("like/{friendId}/{type}")
    public Result addFriend(@PathVariable String friendId,@PathVariable String type){
        //1.从请求作用域中得到claims对象(JWT)
        Claims claims = (Claims) request.getAttribute("claims");
        //2.判断该对象不为空
        if(claims != null){
            //2.1得到访问权限
            String roles = (String) claims.get("roles");
            //2.2判断是否有访问权限
            if(StringUtils.isBlank(roles) || !"user".equals(roles)){
                return new Result(false,StatusCode.ERROR,"无权访问！");
            }
            //2.3判断是否为喜欢，喜欢则添加好友
            if(type.equals("1")){  //点击❤
                //2.3.1进行添加好友
                int i = friendService.addFriend(claims.getId(), friendId);
                //2.3.2判断是否为0，为0则说明是重复添加了
                if(i==0){
                    return new Result(false,StatusCode.ERROR,"不能重复添加！");
                }
                //2.3.3通过调用user微服务，更新用户自己的关注数和对方的粉丝数
                userClient.incfans(friendId,1);
                userClient.incfollow(claims.getId(),1);
            }else {  //点击×
                //2.4将对方添加到非好友列表中
                noFriendService.addNoFriend(claims.getId(),friendId);
            }
            //2.4返回结果
            return new Result(true,StatusCode.OK,"添加好友成功！");
        }
        return new Result(false,StatusCode.ERROR,"请先登录！！");
    }

    //2.删除好友(取消关注)
    @DeleteMapping("{friendId}")
    public Result delete(@PathVariable String friendId){
        //1.从请求作用域中得到claims对象(JWT)
        Claims claims = (Claims) request.getAttribute("claims");
        //2.判断不为空
        if(claims !=null){
            //2.1得到用户身份
            String roles = (String) claims.get("roles");
            //2.2判断是否有权限访问,有权限就进行删除好友
            if(StringUtils.isNotBlank(roles)){
                friendService.delete(claims.getId(),friendId);
                //2.2.1将该用户的关注数-1，将对方的粉丝数-1
                userClient.incfollow(claims.getId(),-1);
                userClient.incfans(friendId,-1);
                //2.2.2返回结果
                return new Result(true,StatusCode.OK,"删除好友成功！");
            }
        }
        //2.3返回结果
        return new Result(false,StatusCode.ERROR,"无权访问！");
    }
}
